﻿app.controller("DanTocCtrl", function ($scope, $controller,$rootScope, BaseSrv, $filter, DanTocSrv) {
    $controller('BaseCtrl', { $scope: $scope });

    $scope.oldValue = {};
    $scope.restore = true;

    GetAll();
 
    function GetAll() {
        DanTocSrv.GetAll().then(function (listObj) {
            $scope.objects = listObj.data;
        }, function () {
        });
    }

    function ResetForm()
    {
        $scope.DMForm.$setPristine();
    }

    $scope.ViewUpdate = function (obj) {
        $('#myModal').unbind('hidden.bs.modal');
        $('#myModal').on('hidden.bs.modal', function () {
            if ($scope.restore) {
                BaseSrv.updateObject($scope.oldValue, $scope.obj)
                $scope.$apply();
            }
            ResetForm();
        })
        $scope.oldValue = angular.copy(obj);
        $scope.obj = obj;
    }

    $scope.Add = function () {
        var obj = {
            Id: null,
            STT: null,
            Ma: null,
            Ten: null,
            DienGiai: null,
            GhiChu: null
        };
        $scope.obj = obj;
        ResetForm();
    }

    $scope.Save = function (obj, luuVaDong, luuVaThemMoi) {

        var obj = {
            Id: obj.Id,
            STT: obj.STT,
            Ma: obj.Ma,
            Ten: obj.Ten,
            DienGiai: obj.DienGiai,
            GhiChu: obj.GhiChu
        };

        DanTocSrv.Save(obj).then(function (response) {
            if (response.data.hasOwnProperty("Success")) {
                BaseSrv.ShowError(response);
            }
            else {
               var single_object = $filter('filter')($scope.objects, function (d) { return d.Id === response.data.Id; })[0];
               var index = $scope.objects.indexOf(single_object);
                if (index<0) {
                    $scope.objects.push(response.data);
                }
                if (luuVaThemMoi) {
                    $scope.Add();
                }
                else {
                    BaseSrv.CloseModal("#myModal");
                }
                $scope.oldValue = angular.copy(response.data);
            }
        });
    }

    $scope.Delete = function (obj) {
        BaseSrv.ShowConfirm("");
        $('#confirmModal').unbind('hidden.bs.modal');
        $('#confirmModal').on('hidden.bs.modal', function () {
            if ($rootScope.objConfirm.ConfirmClicked) {
                DanTocSrv.Delete(obj.Id).then(function (response) {
                    if (response.data.hasOwnProperty("Success")) {
                        BaseSrv.ShowError(response);
                    }
                    else {
                        var index = $scope.objects.indexOf(obj);
                        $scope.objects.splice(index, 1);
                    }
                });
            }
        })
    }
});